package com.compass.mobile.ui.activity.static_page.fragment

import LogUtil
import UserInfoManager
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.leanback.widget.OnChildViewHolderSelectedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentHospitalBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.KEY_TOKEN
import com.compass.mobile.framework.constant.LOCAL_PHONE
import com.compass.mobile.framework.constant.YD_USER_ID
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.constant.selfServicePhone
import com.compass.mobile.framework.constant.selfServiceWxCode
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.HospitalBean
import com.compass.mobile.models.Title
import com.compass.mobile.presenters.HomeMenuPresenter
import com.compass.mobile.presenters.HospitalPresenter
import com.compass.mobile.ui.activity.HomePageActivity
import com.compass.mobile.ui.activity.RecommendedDoctorActivity
import com.compass.mobile.ui.activity.static_page.DoctorStaticActivity
import com.compass.mobile.ui.dialog.HomeInquiryDialog
import com.compass.mobile.ui.viewModel.MainViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import toJson

/**
 * Description： 医院列表
 * Date:2024/8/20 9:52
 */
class HospitalFragment : BaseVBFragment<FragmentHospitalBinding>() {
    private val mainViewModel: MainViewModel by activityViewModels()
    private var hospitals: MutableList<HospitalBean> = mutableListOf()
    private var hospitalOther: MutableList<HospitalBean> = mutableListOf()
    private var hosital: HospitalBean? = null
    private var userToken: String? = null
    private var type: String? = null
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter

    companion object {
        //模拟数据
        val titleMenuList: List<Title?>
            get() {
                val titleList: MutableList<Title?> = ArrayList()
                titleList.add(Title("全部"))
                titleList.add(Title("三级"))
//                titleList.add(Title("二级"))
//                titleList.add(Title("社区卫生服务中心"))
//                titleList.add(Title("乡镇卫生院"))
                titleList.add(Title("村医"))
                return titleList
            }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            userToken = it.getString(KEY_TOKEN)

        }
        specialColumn()
        initTitleMenu(requireContext())

    }

    fun setSelect(type: String) {
        this.type = type
        showLoading()
        mainViewModel.getHospitalList()
    }

    private fun setHos() {
        when (type) {
            "2" -> {
                hospitalOther = hospitals
                arrayObjectAdapter.clear()
                arrayObjectAdapter.addAll(0, hospitalOther)
                mBinding?.caseItem?.visible()
                mBinding?.emptyView?.gone()
            }

            "3" -> {
//                val hos=hosital
//                hos?.name="宝鸡市中医医院"
//                hospitalOther.clear()
//                hos?.let {
//                    hospitalOther.add(it)
//                }
//                arrayObjectAdapter.clear()
//                arrayObjectAdapter.addAll(0, hospitalOther)

                mBinding?.caseItem?.gone()
                mBinding?.emptyView?.visible()
            }

            "4" -> {
//                val hos=hosital
//                hos?.name="铜川市第二人民医院"
//                hospitalOther.clear()
//                hos?.let {
//                    hospitalOther.add(it)
//                }
//                arrayObjectAdapter.clear()
//                arrayObjectAdapter.addAll(0, hospitalOther)

                mBinding?.caseItem?.gone()
                mBinding?.emptyView?.visible()
            }

            "5" -> {
//                val hos=hosital
//                hos?.name="渭南中心医院"
//                hospitalOther.clear()
//                hos?.let {
//                    hospitalOther.add(it)
//                }
//                arrayObjectAdapter.clear()
//                arrayObjectAdapter.addAll(0, hospitalOther)

                mBinding?.caseItem?.gone()
                mBinding?.emptyView?.visible()
            }

            "6" -> {
//                val hos=hosital
//                hos?.name="榆林骨科医院"
//                hospitalOther.clear()
//                hos?.let {
//                    hospitalOther.add(it)
//                }
//                arrayObjectAdapter.clear()
//                arrayObjectAdapter.addAll(0, hospitalOther)

                mBinding?.caseItem?.gone()
                mBinding?.emptyView?.visible()
            }

            "7" -> {
//                val hos=hosital
//                hos?.name="汉中市第一人民医院"
//                hospitalOther.clear()
//                hos?.let {
//                    hospitalOther.add(it)
//                }
//                arrayObjectAdapter.clear()
//                arrayObjectAdapter.addAll(0, hospitalOther)
                mBinding?.caseItem?.gone()
                mBinding?.emptyView?.visible()
            }
        }
    }

    @SuppressLint("RestrictedApi")
    fun initTitleMenu(context: Context) {
        mBinding?.gridTitle?.setHorizontalSpacing(dpToPx(10))
        val arrayObjectAdapter = ArrayObjectAdapter(HomeMenuPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(context, arrayObjectAdapter, null)
        mBinding?.gridTitle?.setAdapter(itemBridgeAdapter)
        arrayObjectAdapter.addAll(0, titleMenuList)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
        mBinding?.gridTitle?.setOnChildViewHolderSelectedListener(onChildViewHolderSelectedListener)

    }


    override fun initData() {
        //每次登录清空一次用户信息
        UserInfoManager.clearUserInfo()
        showLoading()
        mainViewModel.getUserPhoneForToken(userToken)
        mainViewModel.loginLiveData.observe(this) {
            dismissLoading()
            LogUtil.e("user===${it?.toJson()}")
            it?.let {
                UserInfoManager.saveAccessToken(it.accessToken)
                UserInfoManager.saveRefreshToken(it.refreshToken)

                if (selectedPosition==0){
                    //走村医流程
//                    DoctorStaticActivity.start(requireContext())
                    RecommendedDoctorActivity.start(requireContext(),comeType)

                }else{
                    HomePageActivity.start(requireContext())
                }


            } ?: kotlin.run {
                showToast("用户信息异常")
            }
        }
        mainViewModel.hospitalListLiveData.observe(this) {
            dismissLoading()
            it?.let { list ->
                hospitals = list
                if (hospitals.size > 1) {
                    hosital = hospitals[1]
                }
                setHos()

            }
        }
        mainViewModel.userLiveData.observe(this) {
            it?.let { info ->
                info.id?.let { loginCode ->
                    //这里保存一次有效的token
                    UserInfoManager.putString(YD_USER_TOKEN, userToken)
                    UserInfoManager.putString(YD_USER_ID, loginCode)
                    UserInfoManager.putString(LOCAL_PHONE, info.mobile)
                } ?: kotlin.run {
                    showToast("爱家健康token失效")
                }
            } ?: kotlin.run {
                dismissLoading()
            }

        }
    }

    private lateinit var inquiryDialog: HomeInquiryDialog.Builder

    // 保存上一个选中的位置 实现高亮显示效果
    var lastSelectedPosition: Int = -1
    private val onChildViewHolderSelectedListener: OnChildViewHolderSelectedListener = object :
        OnChildViewHolderSelectedListener() {
        override fun onChildViewHolderSelected(
            parent: RecyclerView?,
            childViewHolder: RecyclerView.ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            childViewHolder?.itemView?.setBackgroundResource(R.drawable.bg_shape_blue)
            if (lastSelectedPosition != -1) {
                var lastViewHolder = parent?.findViewHolderForAdapterPosition(lastSelectedPosition)
                lastViewHolder?.itemView?.setBackgroundResource(R.drawable.bg_border_health_item)
            }
            lastSelectedPosition = position
            val item = titleMenuList[position]

            if (item?.name == "村医") {
                inquiryDialog =
                    HomeInquiryDialog.Builder(requireActivity(), onBottomClick)
                inquiryDialog.show()




            }
        }
    }


    //保存选中的医院位置（这里暂时这么写 0为村医）
    private var selectedPosition: Int = -1
    private var comeType: Int = 0
    private fun gotoHospital(position:Int,comeType:Int){
        selectedPosition=position
        this.comeType=comeType
        UserInfoManager.saveHospitalId(hospitals[position].id)
        UserInfoManager.saveHospitalCode(hospitals[position].code)
        UserInfoManager.putString(selfServiceWxCode, hospitals[position].selfServiceWxCode)
        UserInfoManager.putString(selfServicePhone, hospitals[position].selfServicePhone)
        UserInfoManager.savePlatformId(hospitals[position].platformId)

        if ( UserInfoManager.getString(YD_USER_ID).isNullOrEmpty()){
            showToast("移动code获取失败,请退出后重新进入")
        }else {
            showLoading()
            UserInfoManager.getString(YD_USER_ID)?.let {
                mainViewModel.boxLogin(UserInfoManager.getString(YD_USER_ID))
            }
        }
    }

    private var onBottomClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, id: String?) {
            gotoHospital(0,codeType)


        }
    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            gotoHospital(position,0)
        }
    }





    @SuppressLint("RestrictedApi")
    fun specialColumn() {
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)
        arrayObjectAdapter = ArrayObjectAdapter(HospitalPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )
        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        arrayObjectAdapter.addAll(0, hospitals)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )

        lifecycleScope.launch {
            //这里延迟500毫秒 确保生效
            delay(500)
            //延迟获取焦点
            mBinding?.caseItem?.requestFocus()

        }
    }

}